﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;

namespace Waterfood.FolderSizeViewer
{
    public class DataCollector
    {
        private FolderData _data;
        private Queue<DirectoryInfo> _todo;

        public static DataCollector Create(FolderData data)
        {
            // TODO read queue
            DataCollector worker = new DataCollector();
            worker._data = data;
            worker._todo = new Queue<DirectoryInfo>();
            worker._todo.Enqueue(new DirectoryInfo(worker._data.Root));
            return worker;
        }

        public void Save()
        {
            string file = _data.RootEscaped + ".que";
            Console.Write("Saving queue to " + file + " ... ");
            Stream writer = File.Create(file);
            BinaryFormatter serializer = new BinaryFormatter();
            serializer.Serialize(writer, _todo);
            writer.Close();
            Console.WriteLine("done.");
        }

        // return true if no more work
        public async Task<bool> DoWork()
        {
            await Task.Yield();
            var dir = _todo.Dequeue();
            _data.AddFolder(dir.FullName);
            try
            {
                foreach (var f in dir.EnumerateFiles())
                {
                    _data.AddFile(f.FullName, f.Length);
                }
                foreach (var d in dir.EnumerateDirectories())
                {
                    _todo.Enqueue(d);
                }
            }
            catch (UnauthorizedAccessException)
            {
            }
            return _todo.Count == 0;
        }
    }
}
